package com.erf.codec;

import com.erf.message.BaseMessage;
import com.erf.tmpdb.DBMap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.util.ReferenceCountUtil;

import java.util.List;

/**
 * @author zhangzy
 * @date 2022/7/10
 */
public class ByteBufToMessageCodec extends ByteToMessageCodec<BaseMessage> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, BaseMessage baseMessage, ByteBuf byteBuf) throws Exception {
        baseMessage.encode(byteBuf);
        System.out.println(byteBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int length = byteBuf.readInt();
        int command = byteBuf.readInt();
        int sequence = byteBuf.readInt();
        Class<?> aClass = DBMap.commandMap.get(command);
        BaseMessage baseMessage = (BaseMessage) aClass.newInstance();
        baseMessage.decode(length, command, sequence, byteBuf);
        list.add(baseMessage);
    }
}
